package validator;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;


@FacesValidator("validator.MyDateValidator")
public class MyDateValidator implements Validator {

	@Override
	public void validate(FacesContext context, UIComponent component, Object value)
			throws ValidatorException {
		String dateString = (String)value;
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
		
		Locale language = context.getViewRoot().getLocale();
		ResourceBundle res =  ResourceBundle.getBundle("i18n",language);
				
				
				
		try {
			date = sdf.parse(dateString);
			if(!sdf.format(date).equals(dateString)){
				throwException(res, "invaliddate");
			}
		} catch (ParseException e) {
			throwException(res, "invaliddateformat");

		}
	}

	private void throwException(ResourceBundle res, String msgKey) {
		String message = 
				  (String) res.getObject(msgKey);
		FacesMessage msg = new FacesMessage(
		        FacesMessage.SEVERITY_WARN,message, null);
		        throw new ValidatorException(msg);
	}



}
